import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:protobuf/protobuf.dart';
import 'package:synchronized/extension.dart';
import 'package:wk_robot2/app/modules/bindtip/views/bindtip_view.dart';
import 'package:wk_robot2/app/modules/video_live/controllers/VideoLiveManager.dart';
import 'package:wk_robot2/app/robot_comm/mqtt_comm_manager.dart';

import '../../../../generated/AlphaResponse.pb.dart';
import '../../../../generated/RTAVEnterRoom.pb.dart';
import '../../../../generated/RTAVExitRoom.pb.dart';
import '../../../../generated/RTAVParams.pb.dart';
import '../../../../generated/RTAVRobotControlCmd.pb.dart';
import '../../../../generated/RTAVRobotPlayTtsCmd.pb.dart';
import '../../../event/DataCallBack.dart';
import '../../../event/MsgContentEvent.dart';
import '../../../event/WkEventListener.dart';
import '../../../logger/Logger.dart';
import '../../../nets/NetWorkManager.dart';
import '../../../robot_comm/cmd_const.dart';
import '../../../utils/CommonUtil.dart';
import '../../../widget/CommonWidgets.dart';
import '../../../widget/tips.dart';
import 'TtsItem.dart';
import 'TtsRepository.dart';
import 'package:flutter/material.dart';

class VideoLiveController extends GetxController with WidgetsBindingObserver {
  String TAG = "videolive";
  VideoLiveManager videoLiveManager = VideoLiveManager();
  var isLocalAudioStated = false.obs;
  var isActionViewExpanded = false.obs;
  var isMoveControlViewShowed = true.obs;
  var isTtsInputConfirmEnabled = false.obs;
  var ttsList = <TtsItem>[].obs;
  var lengthWordEnterd = 0.obs;
  var isPortrait = true.obs;
  var containSentiveWord = false.obs;
  var ttsTextTips = "".obs;
  var currentPlayingAction = ''.obs;
  int? _videoViewId;
  String _remoteUserId = "";
  var isVideoLoading = true.obs;
  var isMoving = false.obs;  // 是否在移动或者转动头部
  var _isProcessDialogShowed = false; // 做动作的过程弹窗是否弹出
  var _isSingleBtnDialogShowing = false;

  var isConnectionLost = false.obs;
  final String connectionLostErrorText = "网络连接中断";
  var isPowerBelow30 = false.obs; // 电量在20-30
  final String powerBelow30ErrorText = "机器人电量较低，请注意充电";
  var isPowerBelow20 = false.obs; // 电量是否低于20
  final String powerBelow20ErrorText = "机器人电量低，视频通话中断";

  var isConnectionLostOver10s = false.obs;
  Timer? _timer;
  StreamSubscription? _powerSubscription;

  final TextEditingController ttsInputController = TextEditingController();
  TtsItem? currentEditTtsItem; // 当前编辑的tts

  late StreamSubscription<List<ConnectivityResult>> _subscription;
  @override
  void onInit() {
    super.onInit();
    videoLiveManager.init();
    TtsRepository().getAllTtsItems().then((list) {
      ttsList.addAll(list.reversed);
    });
    _sendEnterRoomCmd();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
    if((CommonUtil.getCurrentSelectedRobot().powerValue??0) < 30){
      isPowerBelow30.value = true;
    }

    _subscription = Connectivity().onConnectivityChanged.listen((List<ConnectivityResult> results) {
      if(results.length == 1){
        if(results[0] == ConnectivityResult.none){
          isConnectionLost.value = true;
          _timer = Timer(Duration(seconds: 10), () {
            isConnectionLost.value = false;
            isConnectionLostOver10s.value = true;
            _showSingleBtnDialog(Get.context!, "", "手机无网络，视频通话中断",
                btnText: "“知道了", WkEventListener(onClick: (v) {
                  Get.back();
                }));
          });
        }
      }
      if(results.contains(ConnectivityResult.wifi) || results.contains(ConnectivityResult.mobile)){
        isConnectionLostOver10s.value = false;
        isConnectionLost.value = false;
        _timer?.cancel();
      }

    });
  }

  @override
  void onReady() {
    super.onReady();
    _powerSubscription = eventBus.on<ProductContentEvent>().listen((event) {
      if(event.code == ROBOT_LIST_HAVE_CHANGED) {
        int powervalue = CommonUtil.getCurrentSelectedRobot().powerValue ?? 100;
        if(powervalue < 20){
          isPowerBelow30.value = false;
          isPowerBelow20.value = true;
          _powerSubscription?.cancel();
          if (_isProcessDialogShowed) {
            Navigator.of(Get.context!).pop(); // 关闭弹窗
          }
          _showSingleBtnDialog(Get.context!, "", "机器人电量过低，无法进行视频通话",
              btnText: "“知道了", WkEventListener(onClick: (v) {
                Get.back();
              }));
        }else if(powervalue < 30 && powervalue >= 20){
          isPowerBelow30.value = true;
          isPowerBelow20.value = false;
        }else{
          isPowerBelow30.value = false;
          isPowerBelow20.value = false;
        }
      }
    });
  }

  @override
  void onClose() {
    print('onClose');
    exitRoom();
    _powerSubscription?.cancel();
    _subscription.cancel();
    super.onClose();
  }

  Future<void> changeScrennDirection(bool isPortraitNew) async {
    print("$TAG, isPortrait: ${isPortrait.value},  isPortraitNew: $isPortraitNew");
    if (isPortrait.value == isPortraitNew) {
      return;
    }

    if(isPortraitNew){
      await SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
      ]);
      // await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge,
      //     overlays: [SystemUiOverlay.bottom, SystemUiOverlay.top]); // 显示状态栏
      isPortrait.value = isPortraitNew;
    }else{
      await SystemChrome.setPreferredOrientations([
        DeviceOrientation.landscapeLeft,
        DeviceOrientation.landscapeRight,
      ]);
      // await SystemChrome.setEnabledSystemUIMode(
      //     SystemUiMode.immersiveSticky); // 隐藏状态栏
      //print("hhhhhh changeScrennDirection, $isPortraitNew");
      isPortrait.value = isPortraitNew;
    }
  }

  void hideSystemUIMode(bool isPortrait){
    if(isPortrait) {
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge,
          overlays: [SystemUiOverlay.bottom, SystemUiOverlay.top]); // 显示状态栏
    }else{
      SystemChrome.setEnabledSystemUIMode(
          SystemUiMode.immersiveSticky); // 隐藏状态栏
    }
  }

  void startRemoteView(int viewId) {
    print("$TAG, startRemoteView, _remoteUserId: $_remoteUserId viewId: $viewId");
    _videoViewId = viewId;
    if(_remoteUserId.isNotEmpty){
      isVideoLoading.value = false;
        videoLiveManager.startRemoteView(_remoteUserId, _videoViewId);
    }
  }

  void exitRoom() {
    videoLiveManager.exitRoom();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge,
        overlays: [SystemUiOverlay.bottom, SystemUiOverlay.top]); // 显示状态栏

    _sendExitRoomCmd();
  }

  WalkDerection _walkDerection = WalkDerection.stop;
  void sendWalkCmd(WalkDerection walkDerection) {
    if(_walkDerection == walkDerection){
      return;
    }
    print("$TAG, newwalkDerection: ${walkDerection.name}");
    _walkDerection = walkDerection;

    RTAVDirectionControlCmd derection = RTAVDirectionControlCmd.DIRECTION_STOP;
    switch (walkDerection) {
      case WalkDerection.left:
        derection = RTAVDirectionControlCmd.DIRECTION_LEFT;
      case WalkDerection.right:
        derection = RTAVDirectionControlCmd.DIRECTION_RIGHT;
      case WalkDerection.forward:
        derection = RTAVDirectionControlCmd.DIRECTION_UP;
      case WalkDerection.left_forward:
        derection = RTAVDirectionControlCmd.DIRECTION_UP_LEFT;
      case WalkDerection.right_forward:
        derection = RTAVDirectionControlCmd.DIRECTION_UP_RIGHT;
      default:
        derection = RTAVDirectionControlCmd.DIRECTION_STOP;
    }
    RTAVMotion motion =
        RTAVMotion(motionType: RTAVMotionType.WALK, direction: derection);
    RTAVControlRequest request = RTAVControlRequest(motion: motion);
    MqttCommManager().sendCmd(CmdConst.IM_RTAV_ROBOT_CONTROL_REQUEST, request,
        (AlphaResponse msg) {
      logger.info("received message: " + msg.toString());
      RTAVControlResponse response =
          RTAVControlResponse.fromBuffer(msg.bodyData);
      if (response.resultCode ==
          CmdConst.IM_RTAV_ROBOT_CONTROL_RESPONSE_FORBIDDEN) {
        _showSingleBtnDialog(
            Get.context!, "", response.errorMsg, null,
            btnText: "知道了");
      }
    });
  }

  void sendTurnHeadCmd(TurnHeadDerection turnHeadDerection) {
    RTAVDirectionControlCmd derection = RTAVDirectionControlCmd.DIRECTION_STOP;
    switch (turnHeadDerection) {
      case TurnHeadDerection.left:
        derection = RTAVDirectionControlCmd.DIRECTION_LEFT;
      case TurnHeadDerection.right:
        derection = RTAVDirectionControlCmd.DIRECTION_RIGHT;
      case TurnHeadDerection.up:
        derection = RTAVDirectionControlCmd.DIRECTION_UP;
      case TurnHeadDerection.down:
        derection = RTAVDirectionControlCmd.DIRECTION_DOWN;
      case TurnHeadDerection.left_up:
        derection = RTAVDirectionControlCmd.DIRECTION_UP_LEFT;
      case TurnHeadDerection.left_down:
        derection = RTAVDirectionControlCmd.DIRECTION_DOWN_LEFT;
      case TurnHeadDerection.right_up:
        derection = RTAVDirectionControlCmd.DIRECTION_UP_RIGHT;
      case TurnHeadDerection.right_down:
        derection = RTAVDirectionControlCmd.DIRECTION_DOWN_RIGHT;
      default:
        derection = RTAVDirectionControlCmd.DIRECTION_STOP;
    }
    RTAVMotion motion =
        RTAVMotion(motionType: RTAVMotionType.MOVE_HEAD, direction: derection);
    RTAVControlRequest request = RTAVControlRequest(motion: motion);
    MqttCommManager().sendCmd(CmdConst.IM_RTAV_ROBOT_CONTROL_REQUEST, request,
        (AlphaResponse msg) {
      logger.info("received message: " + msg.toString());
      RTAVControlResponse response =
          RTAVControlResponse.fromBuffer(msg.bodyData);
    });
  }

  void sendActionCmd(String actionName) {
    if (isPortrait.value) {
      _showProcessDialog();
    } else {
      currentPlayingAction.value = actionName;
    }

    RTAVAction action =
        RTAVAction(type: RTAVActionType.RES_PRESET, actionName: actionName);
    RTAVMotion motion =
        RTAVMotion(motionType: RTAVMotionType.PLAY_ACTION, action: action);
    RTAVControlRequest request = RTAVControlRequest(motion: motion);

    MqttCommManager().sendCmd(CmdConst.IM_RTAV_ROBOT_CONTROL_REQUEST, request,
        (AlphaResponse msg) {
      logger.info("play action finished: " + msg.toString());
      RTAVControlResponse response =
          RTAVControlResponse.fromBuffer(msg.bodyData);
      currentPlayingAction.value = "";
      if (_isProcessDialogShowed) {
        Navigator.of(Get.context!).pop(); // 关闭弹窗
      }

      if (response.resultCode ==
          CmdConst.IM_RTAV_ROBOT_CONTROL_RESPONSE_FORBIDDEN) {
        _showSingleBtnDialog(
            Get.context!, "", response.errorMsg, null,
            btnText: "知道了");
      }
    });
  }

  void sendStandUpCmd() {
    print("hhhhhh, screenWidth: ${ScreenUtil().screenWidth},  ui width: ${ScreenUtil().scaleWidth}");
    RTAVMotion motion = RTAVMotion(motionType: RTAVMotionType.STAND_UP);
    RTAVControlRequest request = RTAVControlRequest(motion: motion);

    MqttCommManager().sendCmd(CmdConst.IM_RTAV_ROBOT_CONTROL_REQUEST, request,
        (AlphaResponse msg) {
      logger.info("received message: " + msg.toString());
      RTAVControlResponse response =
          RTAVControlResponse.fromBuffer(msg.bodyData);
    });
  }

  void onTTSInputChanged(String text) {
    lengthWordEnterd.value = text.length;
    isTtsInputConfirmEnabled.value =
    (lengthWordEnterd.value > 0 && lengthWordEnterd.value <= 120);
  }

  void saveTTS() {
    if (!isTtsInputConfirmEnabled.value) {
      return;
    }

    String text = ttsInputController.text;
    // 表情检测
    RegExp emojiRegex = RegExp(
      r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])',
    );
    if(emojiRegex.hasMatch(text)){
      ttsTextTips.value = "请不要输入特殊字符";
      return;
    }else{
      ttsTextTips.value = "";
    }

    // 敏感词检测
    NetWorkManager.getInstance().requestBussiness(
        NetWorkManager.SENSETIVE_CHECK,
        {
          'words': text,
        },
        NetWorkManager.methodPOST, DataCallBack(businessCallBack: (data) async {
      if ((data).isEmpty) {
        // 不包含敏感词
        if(currentEditTtsItem != null){ // 更新tts
          currentEditTtsItem?.text = text;
          bool res = await TtsRepository().updateTtsItem(currentEditTtsItem!);
          if (res) {
            ttsInputController.text = '';
            isTtsInputConfirmEnabled.value = false;
            currentEditTtsItem = null;
            lengthWordEnterd.value = 0;
          }

        }else {  // 新增tts
          TtsItem ttsItem = TtsItem(
              timestamp: DateTime
                  .now()
                  .millisecondsSinceEpoch, text: text);
          bool res = await TtsRepository().insertTtsItem(ttsItem);
          if (res) {
            ttsList.insert(0, ttsItem);
            ttsInputController.text = '';
            isTtsInputConfirmEnabled.value = false;
            lengthWordEnterd.value = 0;
          }
        }
        ttsTextTips.value = "";
        FocusScope.of(Get.context!).unfocus();
      } else {
        // 包含敏感词
        ttsTextTips.value = "内容含有违规词汇";
      }
    }), showLoading: false);
  }

  Future<void> deleteTts(TtsItem ttsItem) async {
    CommonWidgets.showConfirmDialog(
        Get.context!,
        "",
        "确认要删除该条播报吗",
        "删除",
        "取消",
        DataCallBack(
            confirmCallBack: (v) async {
              bool res = await TtsRepository().deleteTtsItem(ttsItem);
              if (res) {
                if(ttsItem.timestamp == currentEditTtsItem?.timestamp){
                  currentEditTtsItem = null;
                }
                ttsList.remove(ttsItem);
              }
            },
            cancleCallBack: (v) {}));
  }

  void editTTS(TtsItem ttsItem) {
    currentEditTtsItem = ttsItem;
    ttsInputController.text = ttsItem.text;
    onTTSInputChanged(ttsItem.text);
  }


  void playTTS(TtsItem ttsItem) {
    ttsItem.isPlaying = true;
    ttsList.refresh();
    RTAVPlayTtsRequest request =
        RTAVPlayTtsRequest(tts: ttsItem.text, isStart: true);

    MqttCommManager().sendCmd(CmdConst.IM_RTAV_ROBOT_PLAY_TTS_REQUEST, request,
        (AlphaResponse msg) {
      logger.info("received message: " + msg.toString());
      RTAVPlayTtsResponse response =
          RTAVPlayTtsResponse.fromBuffer(msg.bodyData);
      ttsItem.isPlaying = false;
      ttsList.refresh();
    });
  }

  void stopTTS(TtsItem ttsItem) {
    RTAVPlayTtsRequest request = RTAVPlayTtsRequest(tts: "", isStart: false);

    MqttCommManager().sendCmd(CmdConst.IM_RTAV_ROBOT_PLAY_TTS_REQUEST, request,
        (AlphaResponse msg) {
      logger.info("received message: " + msg.toString());
      RTAVPlayTtsResponse response =
          RTAVPlayTtsResponse.fromBuffer(msg.bodyData);
      ttsItem.isPlaying = false;
      ttsList.refresh();
    });
  }

  Future<void> changeMicState() async {
    _requestMicrophonePermission((bool res) {
      if (res) {
        videoLiveManager.setMicState(!isLocalAudioStated.value);
        isLocalAudioStated.value = !isLocalAudioStated.value;
        if(isLocalAudioStated.value){
          Tips.showToast1("手机麦克风已开启，为避免产生回声和啸叫，请保持手机和机器人距离5米以上！",EasyLoadingToastPosition.top, Duration(milliseconds: 3000) );
        }else{
          Tips.showToast1("手机麦克风已关闭",EasyLoadingToastPosition.top, Duration(milliseconds: 3000) );
        }
      } else {
        logger.info("isMicrophonePermissionGranted is false");
      }
    });
  }

  void _showSingleBtnDialog(BuildContext context,String title,String content,  WkEventListener? wkEventListener,{String btnText = '确定'}) async {
    if(_isSingleBtnDialogShowing){
      return;
    }

    _isSingleBtnDialogShowing = true;
    CommonWidgets.showSingleBtnDialog(context, title, content, btnText: btnText, WkEventListener(onClick: (v) {
      _isSingleBtnDialogShowing = false;
      if(wkEventListener?.onClick != null) {
        wkEventListener?.onClick!(v);
      }
    })
    );
  }

  WalkDerection currentWalkDerection = WalkDerection.stop;
  void onMoveAngleChange(double angle) {
    WalkDerection newWalkDerection = WalkDerection.stop;
    if (angle >= 67.5 && angle <= 112.5) {
      newWalkDerection = WalkDerection.forward;
    } else if (angle > 22.5 && angle < 67.5) {
      newWalkDerection = WalkDerection.left_forward;
    } else if (angle > 112.5 && angle < 157.5) {
      newWalkDerection = WalkDerection.right_forward;
    } else if (angle <= 22.5 || angle > 270) {
      newWalkDerection = WalkDerection.left;
    } else {
      newWalkDerection = WalkDerection.right;
    }
    if (newWalkDerection != currentWalkDerection) {
      currentWalkDerection = newWalkDerection;
      sendWalkCmd(currentWalkDerection);
    }
  }

  void onMoveStop() {
    currentWalkDerection = WalkDerection.stop;
    sendWalkCmd(currentWalkDerection);
  }

  TurnHeadDerection currentTurnHeadDerection = TurnHeadDerection.stop;
  void onHeadMoveChange(double angle) {
    TurnHeadDerection newTurnHeadDerection = TurnHeadDerection.stop;
    if (angle <= 22.5 || angle >= 337.5) {
      newTurnHeadDerection = TurnHeadDerection.left;
    } else if (angle >= 22.5 && angle <= 67.5) {
      newTurnHeadDerection = TurnHeadDerection.left_up;
    } else if (angle >= 67.5 && angle <= 112.5) {
      newTurnHeadDerection = TurnHeadDerection.up;
    } else if (angle >= 112.5 && angle <= 157.5) {
      newTurnHeadDerection = TurnHeadDerection.right_up;
    } else if (angle >= 157.5 && angle <= 202.5) {
      newTurnHeadDerection = TurnHeadDerection.right;
    } else if (angle >= 202.5 && angle <= 247.5) {
      newTurnHeadDerection = TurnHeadDerection.right_down;
    } else if (angle >= 247.5 && angle <= 292.5) {
      newTurnHeadDerection = TurnHeadDerection.down;
    } else if (angle >= 292.5 && angle <= 337.5) {
      newTurnHeadDerection = TurnHeadDerection.left_down;
    }
    if (newTurnHeadDerection != currentTurnHeadDerection) {
      currentTurnHeadDerection = newTurnHeadDerection;
      sendTurnHeadCmd(currentTurnHeadDerection);
    }
  }

  void onHeadMoveStop() {
    currentTurnHeadDerection = TurnHeadDerection.stop;
    sendTurnHeadCmd(currentTurnHeadDerection);
  }

  void _sendEnterRoomCmd() {
    String newuserId = CommonUtil.getLoginUserId().toString();

    RTAVUserInfo rtavUserInfo = RTAVUserInfo(userId: newuserId);
    RTAVRequestParams requestParams = RTAVRequestParams(userInfo: rtavUserInfo);
    RTAVEnterRoomRequest rtavEnterRoomRequest =
    RTAVEnterRoomRequest(reqParams: requestParams);

    MqttCommManager()
        .sendCmd(CmdConst.IM_RTAV_ENTER_ROOM_REQUEST, rtavEnterRoomRequest,
            (AlphaResponse msg) {
          logger.info("received message: " + msg.toString());
          RTAVEnterRoomResponse rTAVEnterRoomResponse =
          RTAVEnterRoomResponse.fromBuffer(msg.bodyData);
          videoLiveManager.enterRoom(
            userInfo: rTAVEnterRoomResponse.userInfo,
              roomInfo: rTAVEnterRoomResponse.roomInfo,
              onUserVideoAvailable:
                  (remoteUserId) {
                _remoteUserId = remoteUserId;
                print("$TAG, onUserVideoAvailable, startRemoteView, _videoViewId: $_videoViewId");
                if(_videoViewId != null) {
                  isVideoLoading.value = false;
                  videoLiveManager.startRemoteView(remoteUserId, _videoViewId);
                }
              },
              onRemoteUserLeaveRoom: () {

              _showSingleBtnDialog(Get.context!, "", "对方已退出视频通话",
                btnText: "知道了", WkEventListener(onClick: (v) {
                  Get.back();
                }));
          },
              onConnectionLost: (){
                //errorTextCenter.value = _connectLost;
              },
            onConnectionAvailable: (){
              isConnectionLostOver10s.value = false;
              isConnectionLost.value = false;
              _timer?.cancel();
            }
          );
        });
  }

  void _sendExitRoomCmd() {
    String userId = CommonUtil.getLoginUserId().toString();

    RTAVExitRoomRequest request = RTAVExitRoomRequest(userId: userId);

    MqttCommManager().sendCmd(CmdConst.IM_RTAV_EXIT_ROOM_REQUEST, request,
            (AlphaResponse msg) {
          logger.info("received message: " + msg.toString());
          RTAVExitRoomResponse response =
          RTAVExitRoomResponse.fromBuffer(msg.bodyData);
        });
  }

  _requestMicrophonePermission(Function(bool res) onResult) async {
    // 检查麦克风权限状态
    var status = await Permission.microphone.status;

    if (status.isDenied) {
      //如果权限被拒绝，则请求权限
      CommonWidgets.showConfirmDialog(
          Get.context!,
          "",
          "请允许使用手机麦克风，以便和机器人进行通话",
          "确定",
          "取消",
          DataCallBack(
              confirmCallBack: (v) async {
                Map<Permission, PermissionStatus> statuses = await [
                  Permission.microphone,
                ].request();
                // 检查用户是否授予了权限
                if (statuses[Permission.microphone] ==
                    PermissionStatus.granted) {
                  print('Microphone permission granted');
                  onResult(true);
                } else {
                  print('Microphone permission denied');
                  onResult(false);
                }
              },
              cancleCallBack: (v) {}));
    } else if (status.isPermanentlyDenied) {
      // 如果是永久拒绝，那么跳转到设置界面
      CommonWidgets.showConfirmDialog(
          Get.context!,
          "",
          "请允许使用手机麦克风，以便和机器人进行通话",
          "前往设置",
          "取消",
          DataCallBack(
              confirmCallBack: (v) async {
                openAppSettings();
              },
              cancleCallBack: (v) {}));
    } else if (status.isGranted) {
      print('Microphone permission already granted');
      onResult(true);
    } else if (status.isRestricted) {
      print('Microphone permission restricted by system');
      onResult(false);
    }
  }

  void _showProcessDialog() {
    _isProcessDialogShowed = true;
    showDialog(
      context: Get.context!,
      barrierDismissible: false, // 用户点击外部区域不会关闭弹窗
      builder: (BuildContext context) {
        return Dialog(
          backgroundColor: Colors.white,
          child: Container(
            height: 340.h,
            width: 320.w,
            //color: Colors.red,
            padding: EdgeInsets.only(
                top: 67.h, left: 62.w, right: 62.w, bottom: 20.h),
            child: Column(
              //mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Image.asset(
                  'assets/images/playing_action.png', // 替换为你的图片路径
                  width: 195.h,
                  height: 162.w,
                ),
                SizedBox(height: 23.h), // 添加一些间距
                Text(
                  '正在执行动作…',
                  style: TextStyle(fontSize: 28.sp, color: Color(0xff3f5579)),
                ),
              ],
            ),
          ),
        );
      },
    );
    //
  }
}

enum WalkDerection {
  left,
  forward,
  right,
  left_forward,
  right_forward,
  stop,
}

enum TurnHeadDerection {
  left,
  up,
  right,
  down,
  left_up,
  right_up,
  left_down,
  right_down,
  stop
}
